from flask import Blueprint, request, jsonify
from app import db
from app.models.Product import Product
from app.models.ProductCategory import ProductCategory
from flask_jwt_extended import jwt_required, get_jwt_identity
from app.utils.response import success_api, fail_api
from app.utils.validator import validate_params
import uuid
from datetime import datetime
from ..base import base

# 创建蓝图

# 获取商品列表
@base.route('/product/list', methods=['GET'])
def get_product_list():
    try:
        # 获取查询参数
        product_name = request.args.get('productName')
        product_type = request.args.get('productType')
        status = request.args.get('status')
        shop_id = request.args.get('shopId')
        page_num = int(request.args.get('pageNum', 1))
        page_size = int(request.args.get('pageSize', 10))

        # 构建查询条件
        query = Product.query
        if product_name:
            query = query.filter(Product.product_name.like(f'%{product_name}%'))
        if product_type:
            query = query.filter(Product.product_type == product_type)
        if status:
            query = query.filter(Product.status == status)
        if shop_id:
            query = query.filter(Product.shop_id == shop_id)

        # 分页查询
        total = query.count()
        products = query.offset((page_num - 1) * page_size).limit(page_size).all()
        
        # 返回结果
        return success_api({
            'total': total,
            'rows': [product.to_dict() for product in products]
        })
    except Exception as e:
        return fail_api(msg=str(e))

# 获取商品详情
@base.route('/product/<product_id>', methods=['GET'])
@jwt_required()
def get_product(product_id):
    try:
        product = Product.query.get(product_id)
        if not product:
            return fail_api(msg='商品不存在')

        return success_api(data=product.to_dict())
    except Exception as e:
        return fail_api(msg=str(e))

# 新增商品
@base.route('/product', methods=['POST'])
@jwt_required()
def add_product():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['productName', 'categoryId', 'shopId', 'price', 'productType', 'status']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 创建商品对象
        product = Product(
            product_id=str(uuid.uuid4()),
            product_name=data.get('productName'),
            category_id=data.get('categoryId'),
            shop_id=data.get('shopId'),
            product_desc=data.get('productDesc'),
            price=data.get('price'),
            original_price=data.get('originalPrice'),
            cover_img=data.get('coverImg'),
            product_type=data.get('productType'),
            status=data.get('status')
        )

        # 保存到数据库
        db.session.add(product)
        db.session.commit()

        return success_api(msg='添加成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 修改商品
@base.route('/product', methods=['PUT'])
@jwt_required()
def update_product():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['productId', 'productName', 'categoryId', 'price', 'status']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 查询商品
        product = Product.query.get(data.get('productId'))
        if not product:
            return fail_api(msg='商品不存在')

        # 更新商品信息
        product.product_name = data.get('productName')
        product.category_id = data.get('categoryId')
        product.product_desc = data.get('productDesc')
        product.price = data.get('price')
        product.original_price = data.get('originalPrice')
        product.cover_img = data.get('coverImg')
        product.product_type = data.get('productType')
        product.status = data.get('status')
        product.update_time = datetime.now()

        # 保存到数据库
        db.session.commit()

        return success_api(msg='修改成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 删除商品
@base.route('/product/<product_id>', methods=['DELETE'])
@jwt_required()
def delete_product(product_id):
    try:
        product = Product.query.get(product_id)
        if not product:
            return fail_api(msg='商品不存在')

        # 从数据库中删除
        db.session.delete(product)
        db.session.commit()

        return success_api(msg='删除成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 获取商品分类列表
@base.route('/product/category/list', methods=['GET'])
def get_category_list():
    try:
        shop_id = request.args.get('shopId')
        if not shop_id:
            categories = ProductCategory.query.filter_by(parent_id='0').order_by(ProductCategory.order_num).all()
        else:
            # 只查询属于指定店铺的分类
            categories = ProductCategory.query.filter_by(shop_id=shop_id).order_by(ProductCategory.order_num).all()
        return success_api(data=[category.to_dict() for category in categories])
    except Exception as e:
        return fail_api(msg=str(e))

# 新增商品分类
@base.route('/product/category', methods=['POST'])
@jwt_required()
def add_category():
    try:
        data = request.get_json()
        
        # 参数校验
        required_fields = ['categoryName', 'shopId']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')

        # 创建分类对象
        category = ProductCategory(
            category_id=str(uuid.uuid4()),
            category_name=data.get('categoryName'),
            parent_id=data.get('parentId', '0'),
            order_num=data.get('orderNum', 0),
            shop_id=data.get('shopId')
        )

        # 保存到数据库
        db.session.add(category)
        db.session.commit()

        return success_api(msg='添加成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))

# 修改商品分类
@base.route('/product/category', methods=['PUT'])
@jwt_required()
def update_category():
    try:
        data = request.get_json()

        # 参数校验
        required_fields = ['categoryId', 'categoryName', 'parentId', 'orderNum']
        if not validate_params(data, required_fields):
            return fail_api(msg='缺少必要参数')
        # 查询分类
        category = ProductCategory.query.get(data.get('categoryId'))
        if not category:
            return fail_api(msg='商品分类不存在')
        # 更新分类信息
        category.category_name = data.get('categoryName')
        category.parent_id = data.get('parentId', '0')
        category.order_num = data.get('orderNum', 0)
        category.update_time = datetime.now()
        # 保存到数据库
        db.session.commit()
        return success_api(msg='修改成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))
# 删除商品分类
@base.route('/product/category/<category_id>', methods=['DELETE'])
@jwt_required()
def delete_category(category_id):
    try:
        category = ProductCategory.query.get(category_id)
        if not category:
            return fail_api(msg='商品分类不存在')

        # 检查是否有子分类
        children = ProductCategory.query.filter_by(parent_id=category_id).first()
        if children:
            return fail_api(msg='该分类下有子分类，无法删除')
            
        # 检查是否有关联商品
        products = Product.query.filter_by(category_id=category_id).first()
        if products:
            return fail_api(msg='该分类下有商品，无法删除')

        # 从数据库中删除
        db.session.delete(category)
        db.session.commit()

        return success_api(msg='删除成功')
    except Exception as e:
        db.session.rollback()
        return fail_api(msg=str(e))